from rest_framework.authentication import BaseAuthentication
from api.models import UserInfo
from rest_framework.exceptions import AuthenticationFailed
from api.extension import return_code


class TokenAuthentication(BaseAuthentication):
    """ 必须认证成功之后才能访问接口 """

    def authenticate(self, request):
        token = request.query_params.get('token')
        # 1. 获取用户请求 & 验证token是否正确
        if not token:
            raise AuthenticationFailed({"code": return_code.AUTH_FAILED, "error": "认证失败"})
        user_object = UserInfo.objects.filter(token=token).first()
        if not user_object:
            raise AuthenticationFailed({"code": return_code.AUTH_FAILED, "error": "认证失败"})
        return user_object, token

    def authenticate_header(self, request):
        return 'Bearer realm="API"'
